package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.entity.*;
import com.itheima.reggie.mapper.OrdersMapper;
import com.itheima.reggie.service.*;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * 订单业务层
 *
 * @author panda
 * @since 2023/1/6 9:29
 */
@Service
public class OrdersServiceImpl
        extends ServiceImpl<OrdersMapper, Orders>
        implements IOrdersService {

    @Autowired
    private IShoppingCartService shoppingCartService;

    @Autowired
    private AddressBookService addressBookService;

    @Autowired
    private IUserService userService;

    @Autowired
    private IOrderDetailService orderDetailService;

    /**
     * 用户下单
     *
     * @param orders
     */
    //涉及两个表的操作要添加事务管理
    @Transactional
    @Override
    public void submit(Orders orders) {
        //1. 获得当前用户id, 查询当前用户的购物车数据
        Long userId = BaseContext.getCurrentId();
        LambdaQueryWrapper<ShoppingCart> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(ShoppingCart::getUserId, userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(queryWrapper);
        if (shoppingCartList == null) {
            throw new CustomException("购物车无数据,请继续购物");
        }
        //2. 根据地址ID, 查询地址数据
        Long addressBookId = orders.getAddressBookId();
        //购物车数据不止一条,而地址数据只有一条
        //所以可以直接理由mp的byId查询地址数据
        AddressBook addressBook = addressBookService.getById(addressBookId);
        if (addressBook == null) {
            throw new CustomException("无收获地址,请添加收货地址");
        }
        //3. 组装订单明细数据, 计算订单总价值，批量保存订单明细
        //将购物车转换成订单明细表
        List<OrderDetail> orderDetails = new ArrayList<>();

        /**
         * 使用baomidou包下的IdWorker,默认生成的是雪花算法
         */
        long orderId = IdWorker.getId();
        /**
         * 在java中,累加这种的都要采用AtomicInteger这种形式的,会更安全
         */
        AtomicInteger orderAccount = new AtomicInteger(0);
        for (ShoppingCart shoppingCart : shoppingCartList) {
            OrderDetail orderDetail = new OrderDetail();
            //复制
            BeanUtils.copyProperties(shoppingCart, orderDetail);
            //定义订单明细表的编号,组装到订单明细表中
            orderDetail.setOrderId(orderId);
            //将订单明细放入到订单明细的list集合当中
            orderDetails.add(orderDetail);
            //计算总价值,要放到订单表当中
            //在java编程中尽量不在使用传统数学方式的加减乘除
            /**
             * //凡是关于钱的算法都要使用BigDecimal的方法来实现加减乘除
             */
            BigDecimal multiply = shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber()));
            //应该将没个订单明细的乘积结果累加,才是订单表的acount值
            orderAccount.addAndGet(multiply.intValue());
        }
        //4. 组装订单数据（订单Id ,日期、状态、价值、订单编号等）, 保存订单数据
        orders.setId(orderId);
        //公司中有固定的订单号生成规范
        orders.setNumber("20230314" + String.valueOf(orderId));
        orders.setStatus(2);
        orders.setUserId(userId);
        orders.setOrderTime(LocalDateTime.now());
        orders.setCheckoutTime(LocalDateTime.now());
        orders.setAmount(new BigDecimal(orderAccount.intValue()));
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        //将地址信息组装一下,省市地区等等,按照公司的信息
        orders.setAddress(addressBook.getProvinceCode()+addressBook.getCityCode()+"...");
        /**
         * //要想知道下单人信息,要在user表中根据userId去查询订单人的名字
         * 所以要在spring容器中userService
         */
        orders.setUserName(userService.getById(userId).getName());
        //将订单表保存
        this.save(orders);
        //将订单明细表保存
        orderDetailService.saveBatch(orderDetails);
        //5. 删除当前用户的购物车列表数据
        LambdaQueryWrapper<ShoppingCart> queryWrapper1 = new LambdaQueryWrapper();
        queryWrapper1.eq(ShoppingCart::getUserId, userId);
        shoppingCartService.remove(queryWrapper1);

    }
}